using System;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;

namespace blog.Lib
{
    public class MQClient
    {
        public ConnectionFactory factory { set; get; }
        public IConnection conn { set; get; }

        public MQClient()
        {
            _init();
        }

        ~MQClient()
        {
            conn.Close();
        }

        private void _init()
        {
            factory = new ConnectionFactory();
            factory.UserName = "admin";
            factory.Password = "123456";
            factory.VirtualHost = "testhost";
            factory.HostName = "localhost";

            conn = factory.CreateConnection();
        }

        public void send(string queueName, string msg)
        {
            IModel channel = conn.CreateModel();
            channel.QueueDeclare(queueName, false, false, false, null);
            channel.BasicPublish("", queueName, null, System.Text.Encoding.UTF8.GetBytes(msg));
        }

        public void consume(string queueName)
        {
            IModel channel = conn.CreateModel();
            channel.QueueDeclare(queueName, false, false, false, null);
            EventingBasicConsumer consumer = new EventingBasicConsumer(channel);
            consumer.Received += (ch, ea) =>
            {
                var body = ea.Body;
                System.Console.WriteLine(System.Text.Encoding.UTF8.GetString(body));
                channel.BasicAck(ea.DeliveryTag, false);
            };
            String consumerTag = channel.BasicConsume(queueName, false, consumer);
            // channel.QueueBind(queueName, "", routingKey: queueName);
            // while(true) {
            //     BasicGetResult re = channel.BasicGet(queueName, true);
            //     if (re != null)
            //     {
            //         var msgBody = System.Text.Encoding.UTF8.GetString(re.Body);
            //         return msgBody;
            //     }
            // }
        }
    }
}
